import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { ApplicationService } from "../../../../service/application.service";
import { Observable } from "rxjs/Observable";
import { Command } from "../../../../shared/toolbar.service";
import { Blade } from "../../../../shared/blade/blade.model";
import { BladeData } from "../../../../shared/blade/blade-data";
import { DialogResult } from "../../../../shared/dialog.service";

import { TurboperCategory } from "../../../../entity/turboper-category.model";
import { TurboperCategoryService } from "../../../../service/turboper-category.service";
import { TurboperCategoryEditComponent } from "../turboper-category-edit/turboper-category-edit.component";

import { TurbStatusService } from "../../../../service/turbstatus.service";
import { SetofvalueService } from "../../../../service/setofvalue.service";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { TurbStatus } from "../../../../entity/turbstatus.model";
import { Setofkey } from "../../../../entity/setofkey.model";
import { Setofvalue } from "../../../../entity/setofvalue.model";

@Component({
  selector: 'app-turboper-category-list',
  templateUrl: './turboper-category-list.component.html',
  styleUrls: ['./turboper-category-list.component.css']
})
export class TurboperCategoryListComponent extends BladeContainerBase<TurboperCategory> {


  /**
   * 子状态列表
   * 
   * @type {TurboperCategory[]}
   * @memberof TurboperCategoryListComponent
   */
  turboperCategorys: TurboperCategory[] = [];
  turbStatus: TurbStatus[] = [];
  setofkeys: Setofkey[] = [];
  setofvalues: Setofvalue[] = [];

  // notAllowWhenStatuAry:string[] = [];
  // generalCategoryAry:string[] =[];

  constructor(
    private application: ApplicationService,
    private turboperCategoryService: TurboperCategoryService,
    private turbStatusService: TurbStatusService,
    private setofvalueService: SetofvalueService,
    private setofkeyService: SetofkeyService,
  ) {
    super();
  }

  ngOnInit() {
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
    ];
    super.ngOnInit();
  }


  /**
   * 初始化数据
   * 
   * @returns {(any | Observable<any> | Promise<any>)} 
   * @memberof TurboperCategoryListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    // this.turboperCategoryService.getTurboperCategorys()
    //   .then(res => {
    //     this.turboperCategorys = [...res];
    //     this.currentEntity = this.turboperCategorys[0];
    //   })
    //   .catch(error => this.bladeData.error = error)
    //   .then(res => this.bladeData.isLoading = false);
    
    let getTurboperCategory = this.turboperCategoryService.getTurboperCategorys();
    let getTurbStatus = this.turbStatusService.getTurbStatus();
    let getSetofKey = this.setofkeyService.getSetofkeys();
    Promise.all([getTurboperCategory, getTurbStatus, getSetofKey])
      .then(res => {
        if (res[0]) {
          this.turboperCategorys = [...res[0]];
        }
        if (res[1]) {
          this.turbStatus = [...res[1]];
        }
        if (res[2]) {
          this.setofkeys = [...res[2]];
        }
        this.turboperCategorys.forEach(o => {
          let notAllowWhenStatuAry = o.notAllowWhenStatus.split('|');
          o.notAllowWhenStatuNames = "";
          notAllowWhenStatuAry.forEach(a => {
            this.turbStatus.forEach(t => {
              Number(a) == t.statusValue ? o.notAllowWhenStatuNames += t.statusName + " | " : '';
            })
          })
          o.notAllowWhenStatuNames = o.notAllowWhenStatuNames.substring(0, o.notAllowWhenStatuNames.lastIndexOf(' | '))
        })
        //获取风机子状态的keyId
        let setofkey: Setofkey = this.setofkeys.find(o => o.keyCode == 'TurbOperGeneralCategory')
        this.setofvalueService.getSetofValuesBykeyID(setofkey.keyId)
          .then(res => {
            if (res) {
              this.setofvalues = [...res]

              this.turboperCategorys.forEach(o => {
                let generalCategoryAry = o.generalCategory.split('|');
                o.generalCategoryNames = "";
                generalCategoryAry.forEach(g => {
                  this.setofvalues.forEach(s => {
                    g == s.valueCode ? o.generalCategoryNames += s.valueDisplay + " | " : '';
                  })
                })
                o.generalCategoryNames = o.generalCategoryNames.substring(0, o.generalCategoryNames.lastIndexOf(' | '));
              })
            }
          })
          .catch(error => this.bladeData.error = error)
        this.currentEntity = this.turboperCategorys[0];
      })

  }

  /**
   * 增加
   * 
   * @param {Blade} blend
   * @memberof TurboperCategoryListComponent
   */
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "turboperCategoryEdit";
    data.title = "新建子状态";
    data.isClosingDisabled = false;
    let obj = {
      turbStatus: this.turbStatus,
      setofvalues: this.setofvalues,
      turboperCategorys: this.currentEntity
    }
    let createKeyBlade = this.bladeService.createBlade(TurboperCategoryEditComponent, data, true, null, obj);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }
  canExeAdd(blend: Blade): boolean {
    return true;
  }


  /**
   * 编辑
   * 
   * @param {Blade} blend 
   * @memberof TurboperCategoryListComponent
   */
  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = "turboperCategoryEdit";
      data.title = this.currentEntity.operCategoryName;
      let obj = {
        turbStatus: this.turbStatus,
        setofvalues: this.setofvalues,
        turboperCategorys: this.currentEntity
      }
      let editKeyBlade = this.bladeService.createBlade(TurboperCategoryEditComponent, data, false, this.currentEntity, obj);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);
    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }


  /**
   * 删除
   * 
   * @param {Blade} blend 
   * @memberof TurboperCategoryListComponent
   */
  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.turboperCategoryService.batchDelete(selectedKeys.map(o => o.operCategoryId))
              .then(res => {
                if (res.code == '200') {
                  super.refresh(undefined);
                }
                if (res.code == '-1') {
                  this.dialogService
                    .showConfirmationDialog("删除失败", res.message);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }

  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }


  /**
   * 单选
   * 
   * @param {HTMLInputElement} event 
   * @param {TurboperCategory} key 
   * @memberof TurboperCategoryListComponent
   */
  onItemCheack(event: HTMLInputElement, key: TurboperCategory) {
    key.isChecked = event.checked;
  }

  /**
   * 全选
   * 
   * @param {HTMLInputElement} event 
   * @memberof TurboperCategoryListComponent
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.turboperCategorys.length > 0) {
      for (let i = 0; i < this.turboperCategorys.length; i++) {
        this.turboperCategorys[i].isChecked = event.checked;
      }
    }
  }
  onSeletedChange(selectedTurboperCategory: TurboperCategory) {
    if (this.currentBlade.childrenCanDeactivate()) {
      this.currentEntity = selectedTurboperCategory;
    }
  }


  /**
   * 获得选中项
   * 
   * @returns {TurboperCategory[]} 
   * @memberof TurboperCategoryListComponent
   */
  getSelected(): TurboperCategory[] {
    if (this.turboperCategorys.length > 0) {
      let filter = this.turboperCategorys.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }
}



// WEBPACK FOOTER //
// ./src/app/module/basic/turboper-category/turboper-category-list/turboper-category-list.component.ts